package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.page.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.RequiredPermission;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RequestMappingHandlerMapping rmhm;
    @Override
    public void save(Permission persmission) {
            permissionMapper.insert(persmission);
    }

    @Override
    public List<Permission> listAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        int count = permissionMapper.queryForCount(qo);
        PageResult pageResult = null;
        if(count == 0){
            pageResult = new PageResult(count, Collections.EMPTY_LIST);
        }
        List<Permission> list = permissionMapper.queryForList(qo);
        return new PageResult(count,list);
    }

    @Override
    //这里是加载权限的操作
    public void reload() {
        List<Permission> permissions = permissionMapper.selectAll();
        //这里使用了set集合中的元素不能存在重复的特性
        Set<String> resourceSet = new HashSet<>();
        for (Permission permission : permissions) {
            //便利取到权限中的每一个表达式的值
            resourceSet.add(permission.getResource());
        }

        Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhm.getHandlerMethods();
        Collection<HandlerMethod> ms = handlerMethods.values();
        String resource = null;
        String name = null;
        //下面是对方法的便利
        for (HandlerMethod m : ms) {
            RequiresPermissions rp = m.getMethodAnnotation(RequiresPermissions.class);
            RequiredPermission pn = m.getMethodAnnotation(RequiredPermission.class);
            if(rp!=null){
                //在这里的操作是如果存在注解的话
                resource =  rp.value()[0];
                name = pn.value();
                //在这里如果不存在的话那么我们在去进行加载的操作
                if(!resourceSet.contains(resource)) {
                    Permission permission = new Permission();
                    permission.setName(name);
                    permission.setResource(resource);
                    permissionMapper.insert(permission);
                }
            }
        }
    }
}
